import hashlib
import requests


def calculate_sha256(file_path):
    sha256_hash = hashlib.sha256()
    with open(file_path, "rb") as f:
        for byte_block in iter(lambda: f.read(4096), b""):
            sha256_hash.update(byte_block)
    return sha256_hash.hexdigest()


class FileUploader:
    def __init__(self, host):
        self.host = host
        self.mime_types = {
            "pdf": "application/pdf",
            "html": "text/html",
            "csv": "text/csv",
            "xls": "application/vnd.ms-excel",
            "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "doc": "application/msword",
            "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "ppt": "application/vnd.ms-powerpoint",
            "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
            "txt": "text/plain",
            "wav": "audio/wav",
            "jpg": "image/jpeg",
            "png": "image/png"
        }

    def send_request(self, file_path):
        sha256_hash = calculate_sha256(file_path)
        print(f"[哈希计算] 文件 {file_path} 的 SHA-256: {sha256_hash}")

        # 读取文件内容
        with open(file_path, "rb") as f:
            file_bytes = f.read()

        def detect_real_extension(file_path):
            with open(file_path, 'rb') as f:
                header = f.read(12)
                if header.startswith(b'\xff\xd8'):
                    return 'jpg'
                if header.startswith(b'\x89PNG\r\n\x1a\n'):
                    return 'png'
                if header.startswith(b'GIF87a') or header.startswith(b'GIF89a'):
                    return 'gif'
                return None
        # 自动检测文件类型
        file_ext = file_path.split('.')[-1].lower()
        content_type = self.mime_types.get(file_ext, "application/octet-stream")
        if file_ext not in self.mime_types:
            print(f"[类型警告] 未知扩展名 {file_ext}，使用默认 Content-Type")
        real_ext = detect_real_extension(file_path) or file_ext
        if real_ext != file_ext:
            print(f"[格式警告] 文件真实格式为 {real_ext.upper()}, 扩展名 {file_ext} 不匹配")
            file_ext = real_ext
            content_type = self.mime_types.get(file_ext, "application/octet-stream")
        # 构造请求头
        headers = {
            "X-Content-Sha256": sha256_hash,
            "Content-Type": content_type,
            "Content-Length": str(len(file_bytes))
        }


        # 发送上传请求
        url = f"https://{self.host}/api/proxy/up?Action=UploadRaw&Version=2022-01-01&Region=cn-north-1&Id={sha256_hash}&Expire=2h"
        print(url)
        response = requests.post(url, headers=headers, data=file_bytes)

        # 处理响应
        print(f"[响应状态] HTTP {response.status_code}")
        try:
            response_data = response.json()
            if "Result" in response_data and "Path" in response_data["Result"]:
                path = response_data["Result"]["Path"]
                download_url = f"https://{self.host}/api/proxy/down?Action=Download&Version=2022-01-01&Path={path}&IsAnonymous=true"
                print(f"[下载链接] {download_url}")
                return download_url
            raise ValueError("响应数据结构异常")
        except Exception as e:
            print(f"[错误处理] 响应解析失败: {str(e)}")
            print(f"[原始响应] {response.text}")
            return None


if __name__ == "__main__":
    uploader = FileUploader("agent.swjtu.edu.cn")
    result = uploader.send_request("C:\\project\\py\\teach_workflow\\docs\\hiagent_api_content.txt")
    print("文件上传成功" if result else "文件上传失败")
    # https://ai-agent.ctf.com.cn/api/proxy/up?action=uploadraw&version=2022-01-01&region=cn-north-1&id=268e3c9ea2f461d92feea3e8e9c3d6765a85d8c444aa47ea3af5cdd60414f2c8&expire=2h
